﻿using System;
using System.Windows.Data;

namespace XmlStudio.Converters {
    /// <summary>
    /// Converter that converts between zoom ratio (double) and its percentage string representation.
    /// </summary>
    public class ZoomConverter : IValueConverter {
        #region IValueConverter Members

        /// <summary>
        /// Converts from double to percentage string.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            if(value is double) {
                double newValue = (double)value * 100;
                return newValue + " %";
            }

            return value;
        }

        /// <summary>
        /// Converts from percentage string back to double.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            if(value is string) {
                var s = value as string;
                var v = new string[]{};
                if(string.IsNullOrEmpty(s)) {
                    return 0.1;
                } else {
                    v = s.Split(' ');
                }

                double val = 0.1;
                try {
                    val = double.Parse(v[0]);
                } catch(FormatException) {
                    return 1.0;
                }

                return val / 100;
            }

            return value;
        }
        #endregion
    }
}